const express = require('express'),
    router = express.Router(),
    fs = require('fs'),
    path = require('path'),
    xlsx = require('node-xlsx'),
    stream = require('stream')

const data = [
    {
        name: 'sheet1哈哈',
        data: [
            ['ID', 'Name', 'Score'],
            ['我是ID', '小明', '我是嘿嘿'],
            ['我是ID', '小明', '我是嘿嘿'],
            ['我是ID', '小明', '我是嘿嘿'],
            ['大麻哈', '老巫婆', '送网上开的'],
            ['大麻哈', '老巫婆', '送网上开的'],
            ['大麻哈', '老巫婆', '送网上开的'],

        ]
    }
];
const buffer = xlsx.build(data);
// fs.writeFile(path.join(__dirname, 'dd.xlsx'), buffer, err => {
//     if (err) {console.log(err);}
//     console.log('Write to xls has finished');
// });
router.get('/excel', excelResponse);
router.post('/excel', excelResponse);

function excelResponse(req, res) {
    res.set('Content-Type', 'application/octet-stream;charset=utf-8;');
    res.set("Content-Disposition", `attachment;filename=${encodeURIComponent('结果呢')}.xlsx`);
    // let data = fs.createReadStream(path.join(__dirname, '../../public/ha.xlsx'));
    // buffer.pipe(res)
    let readStream = new stream.PassThrough();
    readStream.end(buffer);
    readStream.pipe(res);
}

module.exports = router;